package system

import (
	"cubeAdmin/common"
	"cubeAdmin/common/jwtauth"
	"cubeAdmin/common/utils/gconv"
	"cubeAdmin/common/utils/gstr"
	"cubeAdmin/controllers"
	"cubeAdmin/models"
	"encoding/json"
	"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
	"regexp"
	"strings"
	"time"
)

//var ConfigWeb = new(ConfigWebController)

type ConfigWebController struct {
	controllers.BaseController
}

// URLMapping ...
func (c *ConfigWebController) URLMapping() {
	c.Mapping("Post", c.Post)
}

// Index 获取部门列表视图
// @router /index [get]
func (c *ConfigWebController) Index() {
	// 配置ID
	configId := c.GetString("configId", "")
	if configId == "" {
		configId = "1"
	}

	image, _ := beego.AppConfig.String("sys.image")

	// 获取配置列表
	configData := make([]models.SysConfig, 0)
	orm.NewOrm().QueryTable(new(models.SysConfig)).Filter("is_del", 0).All(&configData)
	configList := make(map[string]string)
	for _, v := range configData {
		configList[gconv.String(v.Id)] = v.Name
	}

	// 获取配置项列表
	itemData := make([]models.SysConfigDetail, 0)
	orm.NewOrm().QueryTable(new(models.SysConfigDetail)).
		Filter("config_id", configId).
		//Filter("status", 1).
		Filter("is_del", 0).
		OrderBy("sort").All(&itemData)

	itemList := make([]map[string]interface{}, 0)

	for _, v := range itemData {
		item := make(map[string]interface{})
		item["id"] = v.Id
		item["title"] = v.Title
		item["code"] = v.Code
		item["value"] = v.Value
		item["type"] = v.Type

		if v.Type == "checkbox" {
			// 复选框
			re := regexp.MustCompile(`\r?\n`)
			list := gstr.Split(re.ReplaceAllString(v.Options, "|"), "|")
			optionsList := make(map[string]string)
			for _, val := range list {
				re2 := regexp.MustCompile(`:|：|\s+`)
				item := gstr.Split(re2.ReplaceAllString(val, "|"), "|")
				optionsList[item[0]] = item[1]
			}
			item["optionsList"] = optionsList
			//前端需要切片类型
			item["value"] = strings.Split(v.Value, ",")
		} else if v.Type == "radio" {
			// 单选框
			re := regexp.MustCompile(`\r?\n`)
			list := gstr.Split(re.ReplaceAllString(v.Options, "|"), "|")
			optionsList := make(map[string]string)
			for _, v := range list {
				re2 := regexp.MustCompile(`:|：|\s+`)
				item := gstr.Split(re2.ReplaceAllString(v, "|"), "|")
				optionsList[item[0]] = item[1]
			}
			item["optionsList"] = optionsList

		} else if v.Type == "select" {
			// 下拉选择框
			re := regexp.MustCompile(`\r?\n`)
			list := gstr.Split(re.ReplaceAllString(v.Options, "|"), "|")
			optionsList := make(map[string]string)
			for _, v := range list {
				re2 := regexp.MustCompile(`:|：|\s+`)
				item := gstr.Split(re2.ReplaceAllString(v, "|"), "|")
				optionsList[item[0]] = item[1]
			}
			item["optionsList"] = optionsList
		} else if v.Type == "image" {
			// 单图片
			//item["value"] = utils.GetImageUrl(v.Value)
			item["value"] = image + v.Value
		} else if v.Type == "images" {
			// 多图片
			list := gstr.Split(v.Value, ",")
			itemList := make([]string, 0)
			for _, v := range list {
				// 图片地址
				//item := utils.GetImageUrl(v)
				item := image + v
				itemList = append(itemList, item)
			}
			item["value"] = itemList
		}
		itemList = append(itemList, item)
	}

	// 渲染模板
	c.Data["configId"] = configId
	c.Data["configList"] = configList
	c.Data["itemList"] = itemList
	c.TplName = "system/config_web/index.tpl"
}

// Post @Title 添加部门
// @Description 添加部门
// @Success 200 {object} controllers.Result
// @router / [post]
func (c *ConfigWebController) Post() {
	if c.Ctx.Input.IsPost() {
		// 返回结果
		/*if utils.AppDebug() {
			c.JSON(common.JsonResult{
				Code: -1,
				Msg:  "演示环境，暂无权限操作",
			})
		}*/

		image, _ := beego.AppConfig.String("sys.image")

		var jsonObj map[string]interface{}
		// 在RequestBody中读取Json
		data := c.Ctx.Input.RequestBody
		json.Unmarshal(data, &jsonObj)

		// 遍历处理数据源
		for key, val := range jsonObj {
			// 参数处理
			if key == "checkbox" {
				// 复选框

				item := gstr.Split(key, "__")
				// KEY值
				key = item[0]
			} else if strings.Contains(key, "upimage") {
				// 单图上传
				item := gstr.Split(key, "__")
				// KEY值
				key = item[0]
				if strings.Contains(gconv.String(val), "temp") {
					//image, _ := utils.SaveImage(gconv.String(val), "config")
					image := gconv.String(val)
					// 赋值给参数
					val = image
				} else {
					// 赋值给参数
					val = gstr.Replace(gconv.String(val), image, "")
				}
			} else if strings.Contains(key, "upimgs") {
				// 多图上传
				item := gstr.Split(key, "__")
				// KEY值
				key = item[0]
				// 图片地址处理
				urlArr := gstr.Split(gconv.String(val), ",")
				list := make([]string, 0)
				for _, v := range urlArr {
					if strings.Contains(gconv.String(v), "temp") {
						//image, _ := utils.SaveImage(v, "config")
						//list = append(list, image)
						list = append(list, v)
					} else {
						image := gstr.Replace(v, image, "")
						list = append(list, image)
					}
				}
				// 数组转字符串，逗号分隔
				val = strings.Join(list, ",")
			} else if strings.Contains(key, "ueditor") {
				item := gstr.Split(key, "__")
				// KEY值
				key = item[0]
				// 富文本处理(待完善)
				// TODO...
			}

			var config models.SysConfigDetail
			// 更新记录
			config.Value = gconv.String(val)
			user, _ := jwtauth.GetAdminDetailUser(c.Ctx.Input)
			config.UpdateBy = user.Id
			config.UpdateTime = time.Now()
			//config.Update()
			err := models.UpdateByConfigDetail(&config)
			if err != nil {
				c.Fail("保存失败", common.DatabaseOperationErr)
			}
		}
		// 返回结果
		c.Ok("保存成功")
	}
}
